package javabase.schoolwork.day6_15;

import java.io.BufferedWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author fance
 * @date 18-6-16 上午9:14
 */
public class DynamicProxy implements InvocationHandler {
    private Object target;
    private long st;
    private BufferedWriter writer;
    public DynamicProxy(Object target,BufferedWriter writer) {
        this.writer = writer;
        this.target = target;
    }


    public <T> T getProxy() {
        return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before();
        Object res = method.invoke(target,args);
        writer.write(String.valueOf(after()));
        writer.write("\n");
        writer.flush();
        return res;
    }

    private void before() {
        this.st = System.currentTimeMillis();
    }
    private long after() {
        return System.currentTimeMillis() - st;
    }
}
